package cfengMiddleware.server.controller;

import cfengMiddleware.server.dto.UserAccountDto;
import cfengMiddleware.server.service.UseAccountService;
import com.google.common.util.concurrent.RateLimiter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Cfeng
 * @date 2022/9/20
 */

@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/account")
public class UserAccountController {

    private final UseAccountService accountService;

    //令牌桶方式限流,这里借助工具类,每s放行10个请求
    RateLimiter rateLimiter = RateLimiter.create(10);

    //方便测试，这里就直接使用参数的方式接收
    @GetMapping("/getMoney")
    public ResponseEntity<String> getMoney(UserAccountDto userAccountDto) {
        //阻塞式获取令牌
//        log.info("等待时间" + rateLimiter.acquire());
        //非阻塞式获取令牌
        if(!rateLimiter.tryAcquire(1000, TimeUnit.MILLISECONDS)) {
            log.warn("被限流了，直接返回失败,说明没库存了");
            return new ResponseEntity<>("获取数据失败,被限流了",HttpStatus.OK);
        }
        if(Objects.isNull(userAccountDto.getAccount()) || Objects.isNull(userAccountDto.getUserId())) {
            return new ResponseEntity<>("参数错误",HttpStatus.BAD_REQUEST);
        }
        try {
//            accountService.takeMoney(userAccountDto);
            accountService.takeMoneyWithVersion(userAccountDto);
//            accountService.takeMoneyWithLock(userAccountDto);
//            accountService.takeMoneyWithRedisLock(userAccountDto);
//            accountService.takeMoneyWithZookeeper(userAccountDto);
            return new ResponseEntity<>("提现成功", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("出现错误",HttpStatus.NOT_FOUND);
        }
    }
}
